﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

public partial class Admin_Admin_CapNhatSanPhamChiTiet : System.Web.UI.Page
{
    string MaSP = "";
    public int phanloai = 0;
    int idSP;
    string strGia = "";
    protected void Page_Load(object sender, EventArgs e)
    {
       MaSP = Request.QueryString.Get("MaSP");
       DataDSTableAdapters.SANPHAMTableAdapter spadapter = new DataDSTableAdapters.SANPHAMTableAdapter();
       DataDS.SANPHAMDataTable sptable=spadapter.SANPHAM_LayTheoMaSP(MaSP);
       idSP = sptable[0].Id;
       strGia = sptable[0]["GiaCu"].ToString();
       if (sptable.Rows.Count == 0)
       {
           Response.Write("<script>alert('Không Tồn Tại Sản Phẩm')</script>");
           return;
       }
       if (!this.IsPostBack)
       {
          txtTenSanPham.Text = (string)sptable.Rows[0]["TenSP"];
           txtMoTa.Text = (string)sptable.Rows[0]["MoTa"];
           imgHinhAnh.ImageUrl = (string)sptable.Rows[0]["HinhAnh"];
           txtNhaSanXuat.Text = (string)sptable.Rows[0]["NhaSanXuat"];
           txtSoLuong.Text = ((int)sptable.Rows[0]["SoLuong"]).ToString();
           txtGia.Text = (sptable.Rows[0]["GiaCu"]).ToString();
           chkTrangThaiBan.Checked =(bool) sptable.Rows[0]["TrangThaiBan"];
           
           
           DataDSTableAdapters.DONVITINHTableAdapter dvtadapter = new DataDSTableAdapters.DONVITINHTableAdapter();
           DataDS.DONVITINHDataTable dvttable = dvtadapter.DONVITINH_LayTatCa();
           ddlDonViTinh.DataSource = null;
           ddlDonViTinh.DataSource = dvttable;
           ddlDonViTinh.DataTextField = "TenDonVi";
           ddlDonViTinh.DataValueField = "Id";
           ddlDonViTinh.DataBind();
           string dvt = (string)sptable.Rows[0]["DonViTinh"];
           dvt = dvt.Trim();
           ddlDonViTinh.Text = dvt;
           txtMaPhanLoai.Text = sptable.Rows[0]["Id_PhanLoai"].ToString();

           DataDSTableAdapters.PHANLOAITableAdapter pladapter = new DataDSTableAdapters.PHANLOAITableAdapter();
           DataDS.PHANLOAIDataTable pltable = pladapter.PHANLOAI_LayPhanLoaiTheoIDCha(0);

           TreeNode treenode = new TreeNode();
           treenode.Text = "Phân loại";
           treenode.Value = "0";
           treenode.PopulateOnDemand = true;
           treenode.SelectAction = TreeNodeSelectAction.SelectExpand;
           tvPhanLoai.Nodes.Add(treenode);

           //khuyen mai
           DataDSTableAdapters.KHUYENMAI_CHITIETTableAdapter kmctadapter = new DataDSTableAdapters.KHUYENMAI_CHITIETTableAdapter();
           DataDS.KHUYENMAI_CHITIETDataTable kmcttable = kmctadapter.KHUYENMAI_LayChiTietTheoSP(idSP);
           if(kmcttable.Rows.Count <= 0)
           {
               //ko co khuyenmai -> them moi
               lbKhuyenMaiTitle.Text = "Thêm khuyến mãi mới";
               btnThem.Text = "Thêm";
           }
           else
           {
               //da ton tai khuyen mai -> cap nhat
               lbKhuyenMaiTitle.Text = "Cập nhật khuyến mãi";
               txtNgayBatDau.Text = kmcttable[0].NgayBatDau.ToShortDateString();
               txtNgayKetThuc.Text = kmcttable[0].NgayKetThuc.ToShortDateString();
               txtMoTaKhuyenMai.Text = kmcttable[0].NoiDung;
               int nHinhThuc = kmcttable.Rows.Count;
               string hinhthucCu = "";
               for (int i = 0; i < nHinhThuc; i++ )
               {
                   hinhthucCu += "<tr><td>" + kmcttable[i].TenHinhThuc + "</td><td><input name='oHinhThuc_" + i + "' type='text' style='display:none' value='" + kmcttable[i].Id_HinhThuc + "'/><input name='oGiaTri_" + i + "' type='text' onblur='checkOldValue(" + i + ")' value='" + kmcttable[i].GiaTri + "'/>";
                   if(kmcttable[i].Id_HinhThuc == 1)
                        hinhthucCu+= " Xóa<input name='oXoa_"+i+"' type='checkbox' /></td></tr>";                   
                   
               }
               lbHinhThucCuPlaces.Text = hinhthucCu;
               lbSoLuongHinhThuc.Text = "Thêm sản phẩm, nhập vào số lượng:";
           }           
           //end khuyen mai

       }
       if (tvPhanLoai.SelectedValue != "" && tvPhanLoai.SelectedValue != "0")
       {
           //lbPhanLoai.Text = tvPhanLoai.SelectedValue;
           txtMaPhanLoai.Text = tvPhanLoai.SelectedNode.Text;
       }
       
        
       
    }
    protected void btnCapNhat_Click(object sender, EventArgs e)
    {
        //goi ham kiem tra cac thong so nhap, neu hop le tien hanh

        //cap nhat
        string imageFolder = ConfigurationSettings.AppSettings["IMAGE_FOLDER"];
        string hinhAnh = imgHinhAnh.ImageUrl;
        if (fulHinhAnh.FileName != "")
        {
            hinhAnh = imageFolder + fulHinhAnh.FileName;
            string duongdan = Server.MapPath(hinhAnh);
            fulHinhAnh.SaveAs(duongdan);
        }
        //luu lai gia cu neu gia thay doi
        if(strGia != txtGia.Text)
        {
            DataDSTableAdapters.GIA_SANPHAMTableAdapter gia_spAdapter = new DataDSTableAdapters.GIA_SANPHAMTableAdapter();
            gia_spAdapter.GIA_SANPHAM_Insert(idSP, DateTime.Now, float.Parse(txtGia.Text));
        }

        //cap nhat bang san pham
        DataDSTableAdapters.SANPHAMTableAdapter spadapter = new DataDSTableAdapters.SANPHAMTableAdapter();        
        int mapl;
        if (tvPhanLoai.SelectedValue != "")
            mapl = int.Parse(tvPhanLoai.SelectedValue);
        else
            mapl = int.Parse(txtMaPhanLoai.Text);
        spadapter.SANPHAM_CapNhatTheoMaSP(MaSP, txtTenSanPham.Text, txtMoTa.Text,
            hinhAnh, txtNhaSanXuat.Text, int.Parse(txtSoLuong.Text),
            chkTrangThaiBan.Checked, float.Parse(txtGia.Text), 1,
            ddlDonViTinh.SelectedValue, DateTime.Now, mapl);

        //them thuoc tinh
        string strconnection = ConfigurationManager.ConnectionStrings["SMOConnectionString"].ConnectionString;
        System.Data.SqlClient.SqlConnection connection = new System.Data.SqlClient.SqlConnection(strconnection);
        connection.Open();        
        string query = "select tt.* " +
                       "from PHANLOAI_THUOCTINH pltt, THUOCTINH tt " +
                       "where pltt.Id_ThuocTinh=tt.Id and pltt.Id_PhanLoai=" + mapl;
        System.Data.SqlClient.SqlCommand command = new System.Data.SqlClient.SqlCommand();
        command.CommandText = query;
        command.Connection = connection;
        System.Data.SqlClient.SqlDataReader dr = command.ExecuteReader();
        if (dr.RecordsAffected != 0)
        {
            DataDSTableAdapters.SANPHAM_THUOCTINHTableAdapter spttAdapter = new DataDSTableAdapters.SANPHAM_THUOCTINHTableAdapter();            

            while (dr.Read())
            {
                string id = dr["Id"].ToString();
                string ten = dr["TenThuocTinh"].ToString();
                string giatri = Request.Form.Get(id);
                spttAdapter.CHITIET_THUOCTINH_Update(idSP, int.Parse(id), giatri);            
                
            }

        }
        //end them thuoc tinh

        Response.Write("<script>alert('Cập nhật thành công!')</script>");
        Response.Redirect("Admin_QuanLySanPham.aspx");

    }
 
    protected void tvPhanLoai_TreeNodePopulate(object sender, TreeNodeEventArgs e)
    {
        string idcha = e.Node.Value;
        DataDSTableAdapters.PHANLOAITableAdapter pladapter = new DataDSTableAdapters.PHANLOAITableAdapter();
        DataDS.PHANLOAIDataTable pltable = pladapter.PHANLOAI_LayPhanLoaiTheoIDCha(int.Parse(idcha));
        if (pltable.Rows.Count == 0)
            return;
        foreach (DataDS.PHANLOAIRow row in pltable)
        {
            TreeNode treenode = new TreeNode();
            treenode.Text = row["TenPhanLoai"].ToString();
            treenode.Value = row["Id"].ToString();
            treenode.PopulateOnDemand = true;
            treenode.SelectAction = TreeNodeSelectAction.SelectExpand;
            e.Node.ChildNodes.Add(treenode);

        }
    }
    protected void btnThem_Click(object sender, EventArgs e)
    {
        DataDSTableAdapters.KHUYENMAI_CHITIETTableAdapter kmctadapter = new DataDSTableAdapters.KHUYENMAI_CHITIETTableAdapter();
        DataDS.KHUYENMAI_CHITIETDataTable kmcttable = kmctadapter.KHUYENMAI_LayChiTietTheoSP(idSP);
        if (kmcttable.Rows.Count <= 0)
        {
            //ko co khuyenmai -> them moi
            themKhuyenMai(-1);
        }
        else
        {
            //da ton tai khuyen mai -> cap nhat
            int idKhuyenMai = kmcttable[0].Id;
            //-----them khuyen mai moi neu co
            if (txtSoLuongHinhThuc.Value != "")
                themKhuyenMai(idKhuyenMai);            
            //-----cap nhat/xoa khuyen mai cu
            //---------update MAIN
            DateTime ngaybatdau = DateTime.Parse(txtNgayBatDau.Text);
            DateTime ngaykethuc = DateTime.Parse(txtNgayKetThuc.Text);
            string noidung = txtMoTaKhuyenMai.Text;
            DataDSTableAdapters.KHUYENMAITableAdapter kmAdapter = new DataDSTableAdapters.KHUYENMAITableAdapter();
            kmAdapter.KHUYENMAI_Update(ngaybatdau, ngaykethuc, noidung, idKhuyenMai);
            //---------update CHITIET
            DataDSTableAdapters.CHITIET_KHUYENMAITableAdapter ctkmAdapter = new DataDSTableAdapters.CHITIET_KHUYENMAITableAdapter();
            string xoa;
            int idHinhThuc, giatri, idChiTiet;
            for (int i = 0; i < kmcttable.Rows.Count; i++ )
            {
                xoa = Request.Form.Get("oXoa_" + i);                
                //idHinhThuc = int.Parse(Request.Form.Get("oHinhThuc_" + i));
                //giatri = kmcttable[i].GiaTri;
                idChiTiet = kmcttable[i].Id1;
                if(xoa == "on")
                {                    
                    ctkmAdapter.CHITIETKHUYEMAI_Xoa(idChiTiet);
                }
                else
                {
                    giatri = int.Parse(Request.Form.Get("oGiaTri_" + i));                    
                    ctkmAdapter.CHITIETKHUYENMAI_CapNhat(giatri, idChiTiet);
                }
            }

            
        }
        Response.Write("<script>alert('Thành công!'); location.href='Admin_capnhatsanphamchitiet.aspx?MaSP="+MaSP+"'</script>");
    }
    public void themKhuyenMai(int idKhuyenMai)
    {
        try
        {
            int? idKM = idKhuyenMai;
            if(idKhuyenMai == -1)
            {
                DateTime ngaybatdau = DateTime.Parse(txtNgayBatDau.Text);
                DateTime ngaykethuc = DateTime.Parse(txtNgayKetThuc.Text);
                string noidung = txtMoTaKhuyenMai.Text;                
                DataDSTableAdapters.KHUYENMAITableAdapter kmAdapter = new DataDSTableAdapters.KHUYENMAITableAdapter();
                kmAdapter.KHUYENMAI_Them(ngaybatdau, ngaykethuc, noidung, idSP, ref idKM);
            }
            
            string str = Request.Form.Get(txtSoLuongHinhThuc.Name);
            int soluongHinhThuc = int.Parse(str);
            DataDSTableAdapters.CHITIET_KHUYENMAITableAdapter ctkmAdapter = new DataDSTableAdapters.CHITIET_KHUYENMAITableAdapter();
            for (int i = 0; i < soluongHinhThuc; i++)
            {
                //int hinhthuc = int.Parse(Request.Form.Get("jHinhThuc_" + i).ToString());
                int giatri = int.Parse(Request.Form.Get("jGiaTri_" + i).ToString());
                ctkmAdapter.CHITIETKHUYENMAI_Them(idKhuyenMai, 1/*tang kem*/, giatri);
            }
        }
        catch (System.Exception ex)
        {
        }
    }
}
